<template>
  <div class="fbsj">
    <DaoHanginPage/>
    <div class="page11">
      <el-row>
        

        <el-col :span="24">
          <div class="liebiao">
            <el-table
              :data="productList"
              style="width: 100%"
              fit
              :header-cell-style="{ background: '#f5f7fa', color: '#606266',fontSize: '20px' }"
            >
            <el-table-column prop="cropName" label="作物昵称" show-overflow-tooltip />
              <el-table-column prop="status" label="状态" show-overflow-tooltip>
                <template #default="scope">
                  <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
                    {{ scope.row.status === '正常' ? '正常' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="estimatedTotalYield" label="预计产量" show-overflow-tooltip />
              <el-table-column prop="totalYield" label="实际产量" show-overflow-tooltip />
              <el-table-column prop="plantingAravage" label="种植面积" show-overflow-tooltip />
              <el-table-column prop="beginTime" label="开始时间" show-overflow-tooltip />
              <el-table-column prop="reapTime" label="结束时间" show-overflow-tooltip />
              <el-table-column prop="suggestedRetailPrice" label="建议零售价格" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.suggestedRetailPrice && scope.row.suggestedRetailPrice !== '0'">
                    ¥{{ scope.row.suggestedRetailPrice }}
                  </span>
                  <span v-else style="color: #909399;">未设置</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    :type="scope.row.currentStatus === '已上架' ? 'danger' : 'primary'"
                    @click="handleToggleShelf(scope.row)"
                    :disabled="scope.row.status !== '正常'"
                  >
                    {{ scope.row.currentStatus === '已上架' ? '取消上架' : '上架' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <div class="pagination-container" v-if="total > 0">
              <el-pagination
                @current-change="handlePageChange"
                :current-page="pageNum"
                :page-size="pageSize"
                :total="total"
                layout="total, prev, pager, next, jumper"
                background
                :page-sizes="[10, 20, 50, 100]"
                :prev-text="'上一页'"
                :next-text="'下一页'"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 自定义上架弹窗 -->
    <el-dialog
      v-model="shelfDialogVisible"
      title="商品上架"
      width="600px"
      :close-on-click-modal="false"
      custom-class="shelf-dialog"
    >
      <div class="shelf-dialog-content">
        <div class="dialog-header">
          <el-icon class="header-icon"><Shop /></el-icon>
          <span class="header-text">商品信息完善</span>
        </div>
        
        <el-form :model="shelfForm" label-width="140px" class="shelf-form">
          <el-form-item label="建议零售价格" class="price-item">
            <div class="price-input-group">
              <el-input
                v-model="shelfForm.price"
                placeholder="0.00"
                class="price-input"
                type="number"
                step="0.01"
                min="0.01"
                max="99999.99"
                @input="handlePriceInput"
                @blur="handlePriceBlur"
              >
                <template #prepend>¥</template>
              </el-input>
              <span class="price-unit">元</span>
            </div>
            <div class="form-tip">
              <el-icon><InfoFilled /></el-icon>
              请输入合理的价格（0.01-99999.99元），最多两位小数
            </div>
            <div class="price-preview" v-if="shelfForm.price && shelfForm.price !== '0.00'">
              预览：<span class="preview-price">¥{{ formatPrice(shelfForm.price) }}</span>
            </div>
          </el-form-item>
          
          <el-form-item label="作物展示图片" class="image-item">
            <div class="upload-container">
              <image-upload 
                v-model="shelfForm.cropImage" 
                :limit="5"
                class="crop-image-upload"
              />
              <div class="upload-tip">
                <el-icon><InfoFilled /></el-icon>
                建议上传清晰的作物图片，有助于提升商品吸引力
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            @click="shelfDialogVisible = false" 
            class="cancel-btn"
            size="large"
          >
            取消
          </el-button>
          <el-button 
            type="success" 
            @click="confirmShelf" 
            class="confirm-btn"
            size="large"
            :disabled="!shelfForm.price || shelfForm.price === '0.00'"
          >
            <el-icon><Check /></el-icon>
            确认上架
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { listProduct } from '@/api/ncpsy/management/product'
import { updateArchive } from '@/api/ncpsy/management/archive'
import useUserStore from '@/store/modules/user'
import DaoHanginPage from '@/components/ncpsy/ZSPT/DaoHanginPage/DaoHanginPage.vue'
import ImageUpload from '@/components/ImageUpload'  
import { ElMessage, ElMessageBox } from 'element-plus'
import { Shop, Check, InfoFilled } from '@element-plus/icons-vue'

const userStore = useUserStore()
const productList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const shelfDialogVisible = ref(false)
const shelfForm = ref({
  price: '0.00',
  cropImage: ''
})
const currentRow = ref(null)

// 处理价格输入
const handlePriceInput = (value) => {
  // 移除非数字字符（除了小数点）
  let cleanValue = value.replace(/[^\d.]/g, '')
  
  // 确保只有一个小数点
  const parts = cleanValue.split('.')
  if (parts.length > 2) {
    cleanValue = parts[0] + '.' + parts.slice(1).join('')
  }
  
  // 限制小数点后最多两位
  if (parts.length === 2 && parts[1].length > 2) {
    cleanValue = parts[0] + '.' + parts[1].substring(0, 2)
  }
  
  // 限制最大值
  const numValue = parseFloat(cleanValue)
  if (!isNaN(numValue) && numValue > 99999.99) {
    cleanValue = '99999.99'
  }
  
  // 更新表单值
  shelfForm.value.price = cleanValue
}

// 处理价格失焦
const handlePriceBlur = () => {
  // 如果输入为空，设置为0.00
  if (!shelfForm.value.price || shelfForm.value.price === '') {
    shelfForm.value.price = '0.00'
    return
  }
  
  // 格式化价格，确保有两位小数
  const numValue = parseFloat(shelfForm.value.price)
  if (!isNaN(numValue)) {
    // 确保最小值为0.01
    if (numValue < 0.01) {
      shelfForm.value.price = '0.01'
    } else {
      shelfForm.value.price = formatPrice(numValue)
    }
  } else {
    shelfForm.value.price = '0.00'
  }
}

// 格式化价格显示
const formatPrice = (price) => {
  const numPrice = typeof price === 'string' ? parseFloat(price) : price
  if (isNaN(numPrice)) return '0.00'
  return numPrice.toFixed(2)
}

// 获取农产品列表
const getProductList = async () => {
  try {
    const query = {
      userId: userStore.id,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    
    const response = await listProduct(query)
    if (response.code === 200) {
      productList.value = response.rows
      total.value = response.total
    } else {
      ElMessage.error('获取农产品列表失败: ' + response.msg)
    }
  } catch (error) {
    console.error('获取农产品列表失败:', error)
    ElMessage.error('获取农产品列表失败: ' + (error.message || '未知错误'))
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  pageNum.value = page
  getProductList()
}

// 处理上架/取消上架切换
const handleToggleShelf = (row) => {
  console.log('row:', row)
  // 判断当前是上架还是下架状态
  const isCurrentlyShelved = row.currentStatus === '已上架';
  
  if (isCurrentlyShelved) {
    // 当前已上架，执行取消上架操作
    ElMessageBox.confirm('确定要取消上架该农产品吗？', '确认取消上架', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 构造取消上架数据，将currentStatus改为0（下架）
      const toggleData = {
        ...row,
        cropImage: '',
        suggestedRetailPrice:'0',
        currentStatus: '未上架'
      }
      
      updateArchive(toggleData).then(response => {
        if (response.code === 200) {
          ElMessage.success('取消上架成功')
          // 更新当前行的状态
          row.currentStatus = '未上架'
          
          // 刷新列表以获取最新数据
          getProductList()
        } else {
          ElMessage.error('取消上架失败: ' + response.msg)
        }
      }).catch(error => {
        console.error('取消上架失败:', error)
        ElMessage.error('取消上架失败: ' + (error.message || '未知错误'))
      })
    }).catch(() => {
      ElMessage.info('已取消操作')
    })
  } else {
    // 当前未上架，执行上架操作
    // 显示自定义上架弹窗
    currentRow.value = row
    shelfForm.value = {
      price: '0.00',
      cropImage: ''
    }
    shelfDialogVisible.value = true
  }
}

// 确认上架
const confirmShelf = () => {
  if (!currentRow.value) return
  
  // 确保价格已格式化
  handlePriceBlur()
  
  // 验证价格范围
  const price = parseFloat(shelfForm.value.price)
  if (isNaN(price) || price <= 0) {
    ElMessage.error('请输入有效的价格（大于0）')
    return
  }
  
  if (price > 99999.99) {
    ElMessage.error('价格不能超过99999.99元')
    return
  }
  
  // 构造上架数据
  const toggleData = {
    ...currentRow.value,
    suggestedRetailPrice: formatPrice(price),
    cropImage: shelfForm.value.cropImage,
    currentStatus: '已上架'
  }
  
  console.log('构造的上架数据:', toggleData)
  console.log('建议零售价格:', toggleData.suggestedRetailPrice)
  console.log('作物图片:', toggleData.cropImage)
  
  updateArchive(toggleData).then(response => {
    if (response.code === 200) {
      console.log('后端响应:', response)
      ElMessage.success(`上架成功，建议零售价格：¥${formatPrice(price)}`)
      // 更新当前行的状态
      currentRow.value.currentStatus = '1'
      currentRow.value.suggestedRetailPrice = formatPrice(price)
      currentRow.value.cropImage = shelfForm.value.cropImage
      
      // 关闭弹窗
      shelfDialogVisible.value = false
      
      // 刷新列表以获取最新数据
      getProductList()
    } else {
      ElMessage.error('上架失败: ' + response.msg)
    }
  }).catch(error => {
    console.error('上架失败:', error)
    ElMessage.error('上架失败: ' + (error.message || '未知错误'))
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getProductList()
})
</script>

<style scoped>
.fbsj {
  padding: 20px;
}

.page11 {
  padding: 50px;
}

.title {
  margin: 20px 0;
  line-height: 30px;
}

.title-name {
  font-size: 30px;
  text-align: left;
}

.liebiao {
  border-radius: 15px;
  overflow: hidden;
  min-height: 500px;
  background-color: #ffffff;
  box-shadow: rgba(80, 79, 79, 0.226) -5px -5px 10px;
  margin-bottom: 0;
  padding-bottom: 0;
}

/* 设置表格内容字体 */
:deep(.el-table__body td .cell) {
  font-size: 18px;  /* 内容字体大小 */
}

/* 分页组件样式 */
.pagination-container {
  margin-top: 25px;
  text-align: center;
  padding: 20px 0;
  background: #fafafa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-pagination) {
  padding: 8px 0;
}

:deep(.el-pagination.is-background .btn-prev),
:deep(.el-pagination.is-background .btn-next),
:deep(.el-pagination.is-background .el-pager li) {
  background-color: #ffffff;
  border: 1px solid #d1e7dd;
  border-radius: 6px;
  margin: 0 4px;
  color: #2e7d32;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-pagination.is-background .btn-prev:hover),
:deep(.el-pagination.is-background .btn-next:hover),
:deep(.el-pagination.is-background .el-pager li:hover) {
  background-color: #e8f5e8;
  border-color: #4caf50;
  color: #1b5e20;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(76, 175, 80, 0.2);
}

:deep(.el-pagination.is-background .el-pager li.active) {
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  border-color: #2e7d32;
  color: #ffffff;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(46, 125, 50, 0.3);
}

:deep(.el-pagination__total) {
  color: #2e7d32;
  font-weight: 500;
  margin-right: 15px;
}

:deep(.el-pagination__jump) {
  color: #2e7d32;
  font-weight: 500;
  margin-left: 15px;
}

:deep(.el-pagination__editor.el-input) {
  margin: 0 8px;
}

:deep(.el-pagination__editor .el-input__inner) {
  background: #f1f8e9;
  border: 1px solid #c8e6c9;
  border-radius: 4px;
}

/* 上架弹窗样式 */
:deep(.shelf-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.shelf-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  margin: 0;
  padding: 20px 24px;
}

:deep(.shelf-dialog .el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.shelf-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

:deep(.shelf-dialog .el-dialog__headerbtn:hover .el-dialog__close) {
  color: #e8f5e8;
}

.shelf-dialog-content {
  padding: 24px 0;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding: 0 24px;
}

.header-icon {
  font-size: 24px;
  color: #4caf50;
}

.header-text {
  font-size: 20px;
  font-weight: 600;
  color: #2e7d32;
}

.shelf-form {
  padding: 0 24px;
}

.price-item {
  margin-bottom: 24px;
}

.price-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-input {
  width: 200px;
}

:deep(.price-input .el-input__wrapper) {
  background: #f8fff8;
  border: 2px solid #c8e6c9;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.price-input .el-input__wrapper:hover) {
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

:deep(.price-input .el-input__wrapper.is-focus) {
  border-color: #2e7d32;
  box-shadow: 0 0 0 3px rgba(46, 125, 50, 0.2);
}

.price-unit {
  font-size: 16px;
  color: #2e7d32;
  font-weight: 500;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #78909c;
  margin-top: 4px;
}

.form-tip .el-icon {
  font-size: 14px;
  color: #4caf50;
}

.price-preview {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.preview-price {
  font-weight: 600;
  color: #2e7d32;
  font-size: 16px;
}

.image-item {
  margin-bottom: 24px;
}

.upload-container {
  background: #f8fff8;
  border: 2px dashed #c8e6c9;
  border-radius: 12px;
  padding: 16px;
  transition: all 0.3s ease;
}

.upload-container:hover {
  border-color: #4caf50;
  background: #f1f8e9;
}

.crop-image-upload {
  margin-bottom: 12px;
}

.upload-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #78909c;
  line-height: 1.4;
}

.upload-tip .el-icon {
  font-size: 14px;
  color: #4caf50;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: #f8fff8;
  border-top: 1px solid #e8f5e8;
}

.cancel-btn {
  border: 2px solid #c8e6c9;
  color: #2e7d32;
  background: white;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  border-color: #4caf50;
  background: #f8fff8;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.2);
}

.confirm-btn {
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  border: none;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.confirm-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #45a049 0%, #1b5e20 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(46, 125, 50, 0.3);
}

.confirm-btn:disabled {
  background: #c8e6c9;
  color: white;
  cursor: not-allowed;
}

.confirm-btn .el-icon {
  margin-right: 4px;
}

:deep(.el-form-item__label) {
  color: #2e7d32;
  font-weight: 500;
  font-size: 14px;
}
</style>